package com.ordering.dao.order.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.ordering.constant.ResultResponse;
import com.ordering.dao.order.OrderDao;
import com.ordering.dao.order.OrderItemDao;
import com.ordering.entity.Order;
import com.ordering.entity.OrderItem;
import com.ordering.entity.Page;
import com.ordering.util.DateAndTime;
import com.ordering.util.HibernateUtil;

public class OrderDaoImpl implements OrderDao
{
	private SessionFactory sessionFactory;
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
	
    OrderItemDao orderItemDao = new OrderItemDaoImpl();
    
    @Override
    public int add(Order order , String itemIds) throws Exception
    {
        Session s=null;
        ResultResponse resultResponse = new ResultResponse();
        try{
            s=HibernateUtil.getSession();
            Transaction tran = s.beginTransaction();
            //计算金额并插入记录
            int money = (int)sumMoney(itemIds);
            order.setProductMoney(money);
            order.setRealMoney(money);
            order.setCreateTime(DateAndTime.getCurrentTime());
            order.setStatus(Order.STATUS_WAIT);
            s.save(order);
            tran.commit();
            //更新订单明细表记录
            updateOrderItem(itemIds,order.getId());
            
            return order.getId();
        }catch (Exception e) {
            resultResponse.setMessage(e.getMessage());
            e.printStackTrace();
        }finally{
            if(s!=null)
                s.close();
        }
        return 0;
    }

    @Override
    public int delect(Order order) throws Exception
    {
        Session s=null;
        try
        {
            s=HibernateUtil.getSession();
            Transaction tran = s.beginTransaction();
            s.delete(order);
            tran.commit();
            return 1;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if(s!=null)
                s.close();
        }
        return 0;
    }

    @Override
    public List<Order> get4page(Order order, Page page) throws Exception
    {
        Session s=null;
        s = HibernateUtil.getSession();
        
        //根据order带来的参数拼接查询条件
        StringBuffer sb = new StringBuffer("from Order where 1=1 ");
        //状态
        if(order.getStatus() > 0){
            sb.append(" and status=? ");
        }
        //地址本id
        if(order.getAddrId() > 0){
            sb.append(" and addrId=? ");
        }
        //手机号
        if(StringUtils.isNotBlank( order.getMsisdn())){
            sb.append(" and msisdn=? ");
        }
        //地址
        if(StringUtils.isNotBlank(order.getAddr())){
            sb.append(" and addr like ? ");
        }
        sb.append(" order by createTime asc ");
        
        Query q = s.createQuery(sb.toString());
        
        int i = 0;
        //状态
        if(order.getStatus() > 0){
            q.setInteger(i++, order.getStatus());
        }
        //地址本id
        if(order.getAddrId() > 0){
            q.setInteger(i++, order.getAddrId());
        }
        //手机号
        if(StringUtils.isNotBlank( order.getMsisdn())){
            q.setString(i++, order.getMsisdn());
        }
        //地址
        if(StringUtils.isNotBlank(order.getAddr())){
            q.setString(i++, "%" + order.getAddr() + "%");
        }
        
        q.setFirstResult(page.getBegin());//设置起始行
        q.setMaxResults(page.getPageSize());//每页条数
        List<Order> list = q.list(); //得到每页的数据
        
        if(s != null)
            s.close();
        return list;
    }

	@Override
	public boolean updateStatus(Order order) throws Exception
	{
		Session s=null;
        s=HibernateUtil.getSession();
        StringBuffer sb = new StringBuffer("update Order set status = ? ");
        
        //更新不同的状态，同时药更新其对应的时间
        if(order.getStatus() == Order.STATUS_WAIT){
        	sb.append(", createTime = ? ");
        }else if(order.getStatus() == Order.STATUS_HANDLE){
        	sb.append(", handleTime = ? ");
        }else if(order.getStatus() == Order.STATUS_DELIVER){
        	sb.append(", deliverTime = ? ");
        }else if(order.getStatus() == Order.STATUS_CANCEL){
        	sb.append(", cancelTime = ? ");
        }else if(order.getStatus() == Order.STATUS_OVER){
        	sb.append(", overTime = ? ");
        }else{
        	throw new Exception("订单状态异常");
        }
        //订单说明
        if(StringUtils.isNotBlank(order.getRemark())){
        	sb.append(", remark = ? ");
        }
        //根据id更行
        sb.append(" where id= ? ");
        
        Query q = s.createQuery(sb.toString());
        
        //插入状态
        q.setInteger(0, order.getStatus());
        //插入时间
        q.setString(1, DateAndTime.getCurrentTime());
        //如果有订单说明，则插入说明
        if(StringUtils.isNotBlank(order.getRemark())){
        	q.setString(2, order.getRemark());
        	q.setInteger(3, order.getId());
        }else{
        	q.setInteger(2, order.getId());
        }
        	
        boolean result = q.executeUpdate() > 0;
        
        if(s != null)
        s.close();
        return result;
	}
	
	
	/**
	 * 更新订单子项的状态
	 * @param ids
	 * @return
	 * @throws Exception
	 */
	private boolean updateOrderItem(String ids,int orderId) throws Exception{
		if(StringUtils.isBlank(ids)){
			//如果id为空
			return false;
		}
		//OrderItem 列表
		List<OrderItem> orderItemList  = new ArrayList<OrderItem>();
		OrderItem orderItem;
		//将id组成的字符串按“,”分开
		String[] idArray = ids.split(",");
		for(String idStr : idArray){
			if(StringUtils.isNotBlank(idStr)){
				orderItem = new OrderItem();
				orderItem.setId(Integer.valueOf(idStr.trim()));
				orderItem.setStatus(OrderItem.STATUS_ORDER);
				orderItem.setOrderId(orderId);
				orderItemList.add(orderItem);
			}
		}
		if(orderItemList.isEmpty()){
			//如果没有有效id
			return false;
		}
		//更新订单子项状态
		return orderItemDao.updateStatus(orderItemList);

	}
	/**
	 * 计算金额
	 * @return
	 */
	private long sumMoney(String ids) throws Exception{
	    if(StringUtils.isBlank(ids)){
            //如果id为空
            return 0;
        }
	    
	    //id列表
        List<Integer> itemIdList  = new ArrayList<Integer>();
	    
        //将id组成的字符串按“,”分开
        String[] idArray = ids.split(",");
        for(String idStr : idArray){
            if(StringUtils.isNotBlank(idStr)){
                itemIdList.add(Integer.valueOf(idStr.trim()));
            }
        }
	    
	    List<OrderItem> itemList = orderItemDao.getAllByIds(itemIdList);
        long money = 0;
        for(OrderItem item : itemList){
            money += item.getPrice() * item.getProductNum();
        }
        
        return money;
	}
	@Override
	public long count(Order order) throws Exception {
		Session s=null;
        s = HibernateUtil.getSession();
        
        //根据order带来的参数拼接查询条件
        StringBuffer sb = new StringBuffer("select count(*) from Order where 1=1 ");
        //状态
        if(order.getStatus() > 0){
            sb.append(" and status=? ");
        }
        //地址本id
        if(order.getAddrId() > 0){
            sb.append(" and addrId=? ");
        }
        //手机号
        if(StringUtils.isNotBlank( order.getMsisdn())){
            sb.append(" and msisdn=? ");
        }
        //地址
        if(StringUtils.isNotBlank(order.getAddr())){
            sb.append(" and addr like ? ");
        }
        sb.append(" order by createTime desc ");
        
        Query q = s.createQuery(sb.toString());
        
        int i = 0;
        //状态
        if(order.getStatus() > 0){
            q.setInteger(i++, order.getStatus());
        }
        //地址本id
        if(order.getAddrId() > 0){
            q.setInteger(i++, order.getAddrId());
        }
        //手机号
        if(StringUtils.isNotBlank( order.getMsisdn())){
            q.setString(i++, order.getMsisdn());
        }
        //地址
        if(StringUtils.isNotBlank(order.getAddr())){
            q.setString(i++, "%" + order.getAddr() + "%");
        }
        long result =  ((Number)q.uniqueResult()).longValue();
        return  result;
	}
    @Override
    public Order getById(int id) throws Exception
    {
        Session s=null;
        s = HibernateUtil.getSession();
        
        //根据order带来的参数拼接查询条件
        StringBuffer sb = new StringBuffer("from Order where id = ? ");
        
        Query q = s.createQuery(sb.toString());
        
        q.setInteger(0, id);

        List<Order> list = q.list(); 
        
        if(s != null)
            s.close();
        
        return list != null? list.get(0) : null;
    }


}
